﻿using AutoMapper;
using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.Repistory;
using U.B.WriteApi.Command;

namespace U.B.WriteApi.CommandHander
{
    public class AdduserCommandHander : IRequestHandler<AdduserCommand, ApiResult<object>>
    {
        private readonly IRepistory<User> _userrepistory;
        private readonly IMapper mapper;
        public AdduserCommandHander(IRepistory<User> userrepistory, IMapper mapper)
        {
            _userrepistory = userrepistory;
            this.mapper = mapper;


        }
        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<object>> Handle(AdduserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();
            var user = _userrepistory.GetAll().Where(x => x.UserName == request.UserName).Count();
            if (user > 0)
            {
                result.code = Renum.添加失败;
                result.Message = Renum.添加成功.ToString() + "用户名重复";
            }
            else
            {
                var a = mapper.Map<User>(request);
                var now = DateTime.Now;
                a.UserPwd = "123456";
                a.CreationDate = now;
                a.Creator = "admin";
                a.IsDeleted = false;
                var u = _userrepistory.Add(a);
                result.code = Renum.添加成功;
                result.Message = Renum.添加成功.ToString();
                result.Data = u;
            }
            return Task.FromResult(result);
        }
    }
}
